﻿using System;
using System.IO;
using FluentNHibernate.Cfg;
using log4net.Config;
using MvcStarterKit.Core.Entities;
using NHibernate;
using NHibernate.Cfg;

namespace MvcStarterKit.Infrastructure
{
	public class AppConfig
	{
		public static ISessionFactory SessionFactory;

		public void PerformStartup()
		{
			InitializeLog4Net();
			InitializeNHibernateSessionFactory();
		}

		private void InitializeNHibernateSessionFactory()
		{
			var configuration = BuildConfiguration();

			SessionFactory = configuration.BuildSessionFactory();
		}

		public static Configuration BuildConfiguration()
		{
			return
				Fluently.Configure(
					new Configuration().Configure())
					.Mappings(
						cfg => cfg.FluentMappings.AddFromAssembly(typeof(Product).Assembly)
					).BuildConfiguration();
		}

		private void InitializeLog4Net()
		{
			string configPath = Path.Combine(
				AppDomain.CurrentDomain.BaseDirectory,
				"Log4Net.config");

			var fileInfo = new FileInfo(configPath);
			XmlConfigurator.ConfigureAndWatch(fileInfo);
		}

		public void StartSession()
		{
			var session = SessionFactory.OpenSession();
			session.BeginTransaction();
			var cache = new SessionCache();
			cache.CacheSession(session);
		}

		public void EndSession()
		{
			var cache = new SessionCache();
			var session = cache.GetSession();
			var tran = session.Transaction;
			if(tran.IsActive)
			{
				tran.Commit();
			}

			session.Dispose();
		}
	}
}
